package com.wn.ziroom.listener;

import com.rabbitmq.client.Channel;
import com.wn.ziroom.service.OrderService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Component
public class DeadQueueListener {

    private OrderService orderService;

    @Autowired
    public void setOrderService(OrderService orderService) {
        this.orderService = orderService;
    }

    @RabbitListener(queues = "DEAD_QUEUE")
    public void deadQueueListener(Message message, Channel channel) throws IOException {
        byte[] body = message.getBody();
        String orderNumber = new String(body, StandardCharsets.UTF_8);
        String substring = orderNumber.substring(4);

        String state = orderService.checkOrderState(substring);

        if (state.equals("1")){
            orderService.changeOrderStateToThree(substring);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);

        }else {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }
        
    }
}
